package com.tanhua.gateway.filters;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanhua.commons.utils.JwtUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Xiao
 * @version 1.0
 * @description 鉴权管理器
 * @date 2021/11/3
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    //从yml注入无须校验的链接 --> 配置文件中以逗号相隔的数据会自动转为数组
//    @Value("#{'${gateway.excludedUrls}'.split(',')}")
    @Value("${gateway.excludedUrls}")
    public List<String> excludedUrls;
    /**
     * 过滤器核心业务代码
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //放行不需要权限校验的链接
        String path = exchange.getRequest().getURI().getPath(); //获取请求路径
        System.out.println("访问URL：" + path);
        if (excludedUrls.contains(path)) {
            return chain.filter(exchange);
        }
        //获取token并校验(xxx/Bearer xxx)    前端Vue的token可能会在前面加上Bearer，如"Bearer token"
        String token = exchange.getRequest().getHeaders().getFirst("Authorization");
        if (StringUtils.isNotEmpty(token)) {
            token = token.replace("Bearer ", "");
        }
        boolean verifyToken = JwtUtils.verifyToken(token);
        //如果校验失败，拦截、响应错误状态
        if (!verifyToken) {
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("errCode", 401);
            responseData.put("errMessage", "用户未登录");
            return responseError(exchange.getResponse(), responseData);
        }
        //校验成功，放行
        return chain.filter(exchange);
    }

    /**
     * 构造响应错误数据 --》 将传入的map集合转为JSON响应到页面
     * @param response
     * @param responseData  Map集合(封装了相应数据)
     * @return
     */
    private Mono<Void> responseError(ServerHttpResponse response, Map<String, Object> responseData){
        // 将信息转换为 JSON
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] data = new byte[0];
        try {
            data = objectMapper.writeValueAsBytes(responseData);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 输出错误信息到页面
        DataBuffer buffer = response.bufferFactory().wrap(data);
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        return response.writeWith(Mono.just(buffer));
    }

    /**
     * 配置执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
